package com.tianma.demo.service.impl;

import com.tianma.demo.dao.OrderDao;
import com.tianma.demo.dao.ProductDao;
import com.tianma.demo.model.Order;
import com.tianma.demo.model.Product;
import com.tianma.demo.service.OrderService;
import com.tianma.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.PipedReader;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderDao orderDao;

    @Override
    @Transactional
    public boolean insertOrder(Long userId, Long productId, int quantity) {
        // 获取产品
        Product product = productService.getProduct(productId);
        // 比较库存和购买数量
        if (product.getStock() < quantity) {
            // 库存不足
            return false;
        }
        // 扣减库存
        productService.decreaseProduct(productId, quantity);
        // 初始化购买记录
        Order order = initOrder(userId, product, quantity);
        orderDao.insertOrder(order);

        return true;
    }

    private Order initOrder(Long userId, Product product, int quantity) {
        Order order = new Order();
        order.setNote("购买日志，时间：" + System.currentTimeMillis());
        order.setPrice(product.getPrice());
        order.setProductId(product.getId());
        order.setQuantity(quantity);
        double totalPrice = product.getPrice() * quantity;
        order.setTotalPrice(totalPrice);
        order.setUserId(userId);

        return order;
    }
}
